package com.flexfiltering.view.util 
{
import mx.collections.ArrayCollection;
import mx.collections.ICollectionView;
import mx.collections.IList;
import mx.collections.ListCollectionView;
import mx.collections.XMLListCollection;

public class CollectionUtil
{
	public static function objectToCollection ( object:Object ) : ICollectionView
	{
		var collection:ICollectionView;
		
		if (object is Array)
        {
            collection = new ArrayCollection(object as Array);
        }
        else if (object is ICollectionView)
        {
            collection = ICollectionView(object);
        }
        else if (object is IList)
        {
            collection = new ListCollectionView(IList(object));
        }
		else if (object is XMLList)
		{
			collection = new XMLListCollection(object as XMLList);
		}
        else
        {
            collection = new ArrayCollection([object]);
        }
        
        return collection;
	}
	
	public static function filterCollection ( source:Array,
											  indexString:String, 
											  prefix:String ) : Array
	{
		var output:Array = [];
		
		if ( prefix == "" )
		{
			return output;
		}
		
		
		var i:Number = 0;
		var pos:Number = 0;
		var index:int = 0;
		var count:int = 0;
		
		while(i > -1){
		
			pos = indexString.indexOf(prefix, i);
		
			if(pos > -1)
			{
				index = int( indexString.substring(indexString.indexOf("<", pos)+1, indexString.indexOf(">", pos)) );
				
				output.push(source[index]);
				count++;
				
				//fix : Bug # 1628014: once a match was found this index was not being advanced to the new row in the grid so multiple rows were being returned
				//in the case of the same term applying twice in a row.
				i = indexString.indexOf(">", pos);
			}
			else
			{
				i = pos;
			}
		}
		return output;
	}

}
}